<template>
	<!------------------------- 规格弹窗 ------------------------->
	<!---------    说明
      此组件为规格展示与交互组件，用于快速下单商品多规格显示，商品详情页面规格显示
      props：
        data      ———— 商品信息
        pageType  ———— 页面类型(quickPlaceOrder,detail)
      method：
        closePopup  ———— 关闭弹窗
        addCart     ———— 加购物车
        buyNow      ———— 直接购买
   -->
	<div class="popup-content">
		<svg-icon icon-class="delete-2" class="color-gray fs-26 popup-close" @goPage="closePopup" />
		<div class="pb-170 pos-r" style="z-index:1;">
			<div class="flex pb-30 hb">
				<img-box class="is-200 br-10 flex-s-0" :img-url="changeData.ThumbnailUrl410" />
				<div class="prductItem-detail ml-20 flex-1">
					<!-- <p class="text-show-line-2 mb-10 fs-24">{{ changeData.ProductName }}</p> -->
					<div v-if="switch85 == 1">
						<p v-show="V_GradePrice && ActivityType == 0" class="color-primary fs-40">
							<span class="fs-26">￥</span>{{ parseFloat(Number(V_GradePrice * Number(activeUnitRatio)).toFixed(2)) }}<span
								class="fs-26">/{{ activeUnitName }}</span>
						</p>
						<p v-show="V_GradePrice && (ActivityType == 1 || ActivityType == 6)" class="color-primary fs-40">
							<span class="fs-26">￥</span>{{ changeData.ActivityPrice }}<span class="fs-26">/{{ activeUnitName }}</span>
						</p>
					</div>
					<div v-else>
						<p v-show="V_GradePrice && ActivityType == 0" class="color-primary fs-40">
							<span class="fs-26">￥</span>{{ parseFloat(Number(V_GradePrice).toFixed(2)) }}<span
								v-show="changeData.BaseUnit" class="fs-26">/{{ changeData.BaseUnit }}</span>
						</p>
						<p v-show="V_GradePrice && (ActivityType == 1 || ActivityType == 6)" class="color-primary fs-40">
							<span class="fs-26">￥</span>{{ changeData.ActivityPrice }}<span v-show="changeData.BaseUnit"
								class="fs-26">/{{
									changeData.BaseUnit }}</span>
						</p>
					</div>

					<!-- <p class="color-gray fs-26">库存 {{ changeData.V_StockSum }}{{ changeData.DefaultUnit }}</p> -->
					<p class="color-gray fs-26" v-if="changeData.StockStr">{{ changeData.StockStr }}</p>
					<p v-show="changeData.MinNum && changeData.MinNum > 0" class="color-gray fs-26">起订 {{ changeData.MinNum }}</p>
					<p v-show="LimitBuy && LimitBuy > 0" class="color-gray fs-26">限购 {{ LimitBuy }}</p>
				</div>
			</div>
			<div v-if="changeData.DefaultUnit" class="skuItem hb">
				<p class="color-gray-light fs-24 mt-20">
					<span>单位</span>
					<span v-show="activeUnitName !== changeData.BaseUnit && changeData.BaseUnit">(1{{ activeUnitName }}={{
						activeUnitRatio }}{{ changeData.BaseUnit }})</span>
					<span>：</span>
				</p>
				<div v-if="changeData.UnitList && changeData.UnitList.length > 0" class="mt-20 flex-v-c flex-wrap">
					<div v-for="(item, index) in changeData.UnitList" :key="index" class="skuBtn"
						:class="activeUnitIndex === index ? 'color-primary' : ''" @click="changeUnit(index)"
						v-if="!(switch85 === 1 && (item != changeData.DefaultUnit) && index == 0)">
						{{ item }}
					</div>
				</div>
				<div v-else class="mt-20 flex-v-c flex-wrap">
					<div class="skuBtn color-primary">{{ changeData.DefaultUnit }}</div>
				</div>
			</div>
			<div class="skuItem">
				<!-- 多规格（第一规格） -->
				<div v-if="changeData.ProductSkuAttrNewList && changeData.ProductSkuAttrNewList.length > 0" class="skuItem hb">
					<p class="color-gray-light fs-24 mt-20">{{ ProductSkuAttrList[0].AttributeName }}：</p>
					<div class="mt-20 flex-v-c flex-wrap">
						<div v-for="(item, index) in ProductSkuAttrList" :key="index" class="skuBtn"
							:class="activeSpecIndex === index ? 'color-primary' : ''" @click="changeSpec(index)">
							{{ item.ValueStr }}
						</div>
					</div>
				</div>
				<!-- 单规格 -->
				<div v-else>
					<div v-for="(item, index) in ProductSkuAttrList[0].SkuList" :key="index" class="flex-s-c mt-24 fs-28 ">
						<div class="flex-2 tal">
							<span>购买数量</span>
						</div>
						<div class="flex-1 tar flex-fe-c">
							<span class="btn-minus flex-s-0 " :class="item.Amount <= 0 ? 'color-shadow' : ''"
								@click="changeAmount(item, item.Amount, item.Stock, -1, changeData.MinNum, activeUnitRatio, item.LimitBuy)">-</span>
							<div class="btn-input-box">
								<input v-model="item.Amount" type="number" class="btn-input"
									@blur="changeAmount(item, item.Amount, item.Stock, 0, changeData.MinNum, activeUnitRatio, item.LimitBuy)">
							</div>
							<span class="btn-plus flex-s-0"
								:class="item.Amount >= item.Stock || (item.Amount >= item.LimitBuy && item.LimitBuy > 0) ? 'color-shadow' : ''"
								@click="changeAmount(item, item.Amount, item.Stock, 1, changeData.MinNum, activeUnitRatio, item.LimitBuy)">+</span>
						</div>
					</div>
				</div>

				<!-- 第二规格 -->
				<div v-if="secondSpecList && secondSpecList.length > 0" class="skuItem">
					<div class="flex-s-c mt-24 color-gray-light fs-24 ">
						<div class="flex-1 tal">{{ secondSpecList[0].AttributeName || '规格' }}</div>
						<div class="flex-1 tac">库存</div>
						<div class="flex-1 tar">购买数量</div>
					</div>
					<div v-for="(item, index) in secondSpecList" :key="index" class="flex-s-c mt-24 fs-28 ">
						<div class="flex-1 tal">{{ item.AttributeNameSingle }}</div>
						<div class="flex-1 tac">{{ item.StockStr }}</div>
						<div class="flex-1 tar flex-fe-c">
							<span class="btn-minus flex-s-0 " :class="item.Amount <= 0 ? 'color-shadow' : ''"
								@click="changeAmount(item, item.Amount, item.Stock, -1, changeData.MinNum, activeUnitRatio, item.LimitBuy)">-</span>
							<div class="btn-input-box">
								<input v-model="item.Amount" type="number" class="btn-input"
									@blur="changeAmount(item, item.Amount, item.Stock, 0, changeData.MinNum, activeUnitRatio, item.LimitBuy)">
							</div>
							<span class="btn-plus flex-s-0"
								:class="item.Amount >= item.Stock || (item.Amount >= item.LimitBuy && item.LimitBuy > 0) ? 'color-shadow' : ''"
								@click="changeAmount(item, item.Amount, item.Stock, 1, changeData.MinNum, activeUnitRatio, item.LimitBuy)">+</span>
						</div>
					</div>
				</div>
			</div>
			<div class="fixed-bottom bottom-box">
				<button v-show="pageType === 'quickPlaceOrder'" class="btn-large color-white bg-primary"
					@click="addCart">加入购物车</button>
				<button
					v-show="pageType === 'detail' && ActivityType == 0 && changeData.IsFutures != 3 && changeData.IsFutures != 7"
					class="btn-half color-white bg-second br-left" @click="addCart">加入购物车</button>
				<button
					v-show="pageType === 'detail' && ActivityType == 0 && changeData.IsFutures != 3 && changeData.IsFutures != 7"
					class="btn-half color-white bg-primary br-right" @click="buyNow">立即购买</button>
				<button
					v-show="pageType === 'detail' && ActivityType == 0 && changeData.IsFutures == 3 || changeData.IsFutures == 7"
					class="btn-large color-white bg-primary" @click="buyNow">立即购买</button>
				<button v-show="pageType === 'detail' && ActivityType == 1" class="btn-large color-white bg-primary"
					@click="buyNow">发起拼团</button>
				<button v-show="pageType === 'detail' && ActivityType == 6" class="btn-large color-white bg-primary"
					@click="buyNow">{{ changeData.ActivityPrice ? '周期购买' : '免费领取' }}</button>
			</div>
		</div>
	</div>
</template>

<script>
import imgBox from 'components/imgBox'
import { AddOrEditUserCarList } from 'api/product'
import { GetUpgradeGradeLink } from 'api/member'

export default {
	name: 'ProductSpec',
	components: {
		imgBox
	},
	props: {
		data: {
			// 数据
			type: Object,
			required: true
		},
		ActivityData: {
			// 数据
			type: Object,
			required: false
		},
		fresh: {
			type: Boolean,
			required: false,
			default: false
		},
		storeId: {
			type: String,
			required: false,
			default: ''
		},
		pageType: {
			// 按钮类型
			type: String,
			required: false,
			default: 'quickPlaceOrder'
		},
		switch85: {
			type: Number,
			required: false,
			default: 0
		},
		switch203: {
			type: Number,
			required: false,
			default: 0
		},
		ActivityType: {
			type: Number,
			required: false,
			default: 0
		},
		GradeId: {
			type: Number,
			required: false,
			default: 0
		},
		Source: {
			type: Number,
			required: false,
			default: 1
		},
		switch7: {
			type: Number,
			required: false,
			default: 0
		},
	},
	data() {
		return {
			changeData: {},
			activeUnitIndex: -1,
			activeUnitName: '',
			activeUnitRatio: 1,
			activeSpecIndex: -1,
			secondSpecList: [],
			cartRequestObj: [],
			ProductSkuAttrList: [],
			V_GradePrice: '',
			LimitBuy: '',
		}
	},
	watch: {
		data(newVal, oldVal) {
			console.log('商品变化')
			this.init()
		},
		fresh(newVal, oldVal) {
			console.log('gengxin')
			this.init()
		}
	},
	created() {

		this.init()
	},
	methods: {
		init() {
			console.log(123123)
			// this.activeUnitIndex = -1
			// this.activeUnitName = ''
			// this.activeUnitRatio = 1
			// this.activeSpecIndex = -1
			// this.secondSpecList = []
			// this.cartRequestList = []
			// this.changeData = this.data
			// console.log('changeData',this.changeData)
			// this.ProductSkuAttrList = this.changeData.ProductSkuAttrList
			// this.V_GradePrice = this.changeData.V_GradePrice
			// this.LimitBuy = this.changeData.LimitBuy		
			// if (this.changeData.UnitList && this.changeData.UnitList.length > 0) {
			// 	this.changeData.UnitList.forEach((item, index) => {
			// 		if (this.changeData.DefaultUnit === item) {
			// 			this.activeUnitIndex = index
			// 			this.activeUnitName = this.changeData.UnitList[index]
			// 			this.activeUnitRatio = this.changeData.UnitratioList[index]
			// 		}else{
			// 			this.activeUnitName = this.changeData.UnitList[0]
			// 			this.activeUnitRatio = this.changeData.UnitratioList[0]		
			// 			this.activeUnitIndex = 0
			// 		}
			// 	})
			// } else {
			// 	this.activeUnitName = this.changeData.BaseUnit
			// }

			// if (this.switch85 === 1 && this.changeData.BaseUnit != this.changeData.DefaultUnit) {
			// 	this.deleteItem(this.changeData.BaseUnit, this.changeData.UnitList);
			// 	this.deleteItem(1, this.changeData.UnitratioList);
			// 	this.changeData.UnitratioList.shift()
			// 	console.log('this.changeData.UnitList',this.changeData.UnitList)
			// 	console.log('this.changeData.UnitratioList',this.changeData.UnitratioList)
			// 	this.activeUnitName = this.changeData.UnitList[0]
			// 	this.activeUnitRatio = this.changeData.UnitratioList[0]		
			// 	 this.activeUnitIndex = 0
			// }
			this.activeUnitIndex = -1
			this.activeUnitName = ''
			this.activeUnitRatio = 1
			this.activeSpecIndex = -1
			this.secondSpecList = []
			//this.cartRequestList = []
			this.changeData = this.data
			console.log('changeData', this.changeData)
			this.ProductSkuAttrList = this.changeData.ProductSkuAttrList
			this.V_GradePrice = this.changeData.V_GradePrice
			this.LimitBuy = this.changeData.LimitBuy
			if (this.changeData.UnitList && this.changeData.UnitList.length > 0) {
				this.changeData.UnitList.forEach((item, index) => {
					if (this.changeData.DefaultUnit === item) {
						this.activeUnitIndex = index
						this.activeUnitName = this.changeData.UnitList[index]
						this.activeUnitRatio = this.changeData.UnitratioList[index]
					}
				})
			} else {
				this.activeUnitName = this.changeData.BaseUnit
			}

		},

		deleteItem(item, list) {
			// 先遍历list里面的每一个元素，对比item与每个元素是否相等，再利用splice的方法删除
			for (var key in list) {
				if (list[key] === item) {
					list.splice(key, 1)
				}
			}
		},
		// 关闭弹窗
		closePopup() {
			this.$emit('closePopup')
		},

		// 加入购物车
		addCart() {
			console.log('this.cartRequestList', this.cartRequestList)
			this.closePopup()
			this.$emit('addCart', this.cartRequestList)
			// this.cartRequestList = []
			// this.activeUnitName = ''
			// this.activeUnitRatio = 1
		},

		// 直接购买
		buyNow() {
			// this.$emit('buyNow', this.cartRequestList)
			const _obj = {}
			_obj.list = this.cartRequestList
			_obj.isTempCar = true
			_obj.isRemoveAll = true
			if (this.storeId) {
				_obj.storeId = this.storeId
			}
			if (_obj.list && _obj.list.length > 0) {
				if (this.ActivityType == 1) {//拼团
					this.AddGroupOrder(_obj.list[0])
				} else if (this.ActivityType == 6) {//周期购
					console.log(32)
					console.log(_obj)
					this.AddPeriodicBuyOrder(_obj.list[0])
				} else {
					this.AddOrEditUserCarList(_obj)
				}
			} else {
				this.$toast.fail('请添加商品')
			}
		},
		AddGroupOrder(obj) {
			console.log(obj)
			var orderAmount = obj.Amount;
			if (obj.ratio > 1) {
				orderAmount = obj.Amount * obj.ratio;
			}
			if (orderAmount > this.changeData.GroupCount && this.changeData.GroupWay == 1) {
				this.$toast.fail("拼团限量不得大于" + this.changeData.GroupCoun)
				return;
			}
			if (orderAmount > this.changeData.OrderLimitNum && this.changeData.OrderLimitNum > 0) {
				this.$toast.fail("拼团限量不得大于" + this.changeData.OrderLimitNum)
				return;
			}
			if (orderAmount > this.changeData.V_StockSum) {
				this.$toast.fail("商品库存不足")
				return false;
			}
			var carlist = [];
			var param = {
				ProductId: obj.ProductId,
				SkuId: obj.SkuId,
				Amount: orderAmount,
				StoreId: this.storeId,
				RatioUnit: obj.ratioUnit,
				Ratio: obj.ratio,
				GroupId: this.changeData.GroupId
			};
			carlist.push(param);
			localStorage.setItem('GroupSkuList', JSON.stringify(carlist))
			window.location = "/m/group/GroupOrder?id=" + obj.ProductId + "&group_order_id=" + 0 + "&groupType=" + 1;
		},
		AddPeriodicBuyOrder(obj) {
			console.log(obj)
			console.log(this.GradeId)
			var orderAmount = obj.Amount;
			if (obj.ratio > 1) {
				orderAmount = obj.Amount * obj.ratio;
			}
			if (this.ActivityData.RemainQty <= 0) {
				this.$toast.fail("活动名额已满，请关注其他活动")
				return;
			}
			if (this.GradeId > 0) {
				if (this.ActivityData.GradeIds.indexOf(this.GradeId) == -1) {
					var path = '?targetGradeIds=' + this.ActivityData.GradeIds.join(",")
					GetUpgradeGradeLink(path).then(data => {
						if (data.State) {
							if (data.Data.UpgradeLink) {
								this.$dialog.confirm({
									title: '温馨提示',
									message: "参与该活动需升级为" + data.Data.TargetGradeName
								})
									.then(() => {
										window.location = data.Data.UpgradeLink;
									}).catch(() => {
										// on cancel
									});
								return;
							}
							if (data.Data.TargetGradeName) {
								this.$toast.fail("参与该活动需升级为" + data.Data.TargetGradeName)
								return;
							}
						}
						this.$toast.fail("您的会员等级无法购买")
					})
					return;
				}
			}
			if (orderAmount > 1) {
				this.$toast.fail("只能购买一件商品")
				return;
			}
			if (orderAmount > this.changeData.V_StockSum) {
				this.$toast.fail("商品库存不足")
				return false;
			}
			window.location = "/m/Product/PeriodicBuySubmitOrder?activityId=" + this.ActivityData.ActivityId + "&skuId=" + obj.SkuId + "&isRetail=0";
		},
		changeUnit(index) {
			console.log('选择单位---this.changeData.UnitratioList', this.changeData.UnitratioList)
			this.activeUnitIndex = index
			this.activeUnitName = this.changeData.UnitList[index]
			this.activeUnitRatio = this.changeData.UnitratioList[index]
			console.log(this.activeUnitName)
			console.log(this.activeUnitRatio)
			if (this.changeData.ProductAttributesList.length == 0) {
				let item = this.ProductSkuAttrList[0].SkuList[0]
				//this.cartRequestList = [];
				this.changeAmount(item, item.Amount, item.Stock, 0, this.changeData.MinNum, this.activeUnitRatio, item.LimitBuy)
			}
		},
		changeSpec(index) {
			console.log('选择规格---this.changeData.ProductSkuAttrList', this.changeData.ProductSkuAttrList)
			console.log('选择规格---index', index)
			this.activeSpecIndex = index
			this.secondSpecList = this.changeData.ProductSkuAttrList[index].SkuList
			if (this.secondSpecList && this.secondSpecList.length > 0) {
				this.secondSpecList.forEach(item => {
					item.AttributeNameSingle = item.AttributeNameSingle || item.AttributeNameValue
				})
			}
		},
		changeAmount(item, num, stock, type, minNum, UnitRatio, LimitBuy) {
			if (item.IsLock == 1) {
				this.$toast('该商品已禁用')
				return
			}
			if (type == 0 && num >= LimitBuy && LimitBuy !== 0) {
				num = LimitBuy
				this.$toast('已达到限购数量')
			}
			if (type == 1 && num >= LimitBuy && LimitBuy !== 0) {
				this.$toast('已达到限购数量')
				return
			}
			this.$utils.changeAmount(item, num, stock, type, minNum, 1, LimitBuy, this.switch7)
			const _obj = {}
			_obj.ProductId = item.ProductId
			_obj.Amount = item.Amount
			_obj.SkuId = item.ID
			_obj.ratioUnit = this.activeUnitName //选中的单位
			_obj.ratio = UnitRatio //比例
			if (this.storeId) {
				_obj.StoreId = this.storeId
			}
			_obj.Source = this.Source
			let _newObj = true
			this.V_GradePrice = item.V_GradePrice
			this.LimitBuy = item.LimitBuy
			if (this.cartRequestList && this.cartRequestList.length > 0) {
				console.log('cartRequestList', 1)
				console.log('cartRequestList', this.cartRequestList)
				for (let i = 0; i < this.cartRequestList.length; i++) {
					if (_obj.SkuId === this.cartRequestList[i].SkuId && _obj.ProductId === this.cartRequestList[i].ProductId) {
						this.cartRequestList[i].Amount = _obj.Amount
						_newObj = false
						break
					}
				}
			}
			if (_newObj) {
				this.cartRequestList.push(_obj)
				console.log('cartRequestList', 2)
				console.log('cartRequestList', this.cartRequestList)
			}
		},

		AddOrEditUserCarList(obj) {
			AddOrEditUserCarList(obj).then(res => {
				if (res) {
					localStorage.setItem('Wholesale_PayWay', 'buy')
					if (this.storeId) {
						window.location.href = this.$LocalDomain + '/m/retail/productsubmitorder?storeid=' + this.storeId
					} else {
						if (this.switch203 == 1) {
							window.location.href = this.$LocalDomain + '/m/supplier/productsubmitorder?storeid=' + this.storeId
						} else {
							window.location.href = this.$LocalDomain + '/m/product/ProductSubmitOrder?InfoType=1'
						}
					}
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped>
// 弹窗组件
.popup-content {
	padding: 30px;
	position: relative;
	background: $colorF;
	border-radius: 40px 40px 0 0;

	.popup-close {
		position: absolute;
		right: 30px;
		top: 30px;
		z-index: 5;
	}

	.prductItem-detail {
		position: relative;

		.prductItem-p-left {
			position: absolute;
			bottom: 0;
			left: 0;
		}

		.prductItem-p-right {
			position: absolute;
			bottom: 0;
			right: 0;
		}
	}

	.skuItem {
		padding-bottom: 4px;

		.skuBtn {
			position: relative;
			font-size: 28px;
			line-height: 64px;
			padding: 0 30px;
			min-width: 136px;
			border-radius: 8px;
			overflow: hidden;
			margin: 0 20px 20px 0;
			text-align: center;

			&:before {
				content: '';
				position: absolute;
				height: 100%;
				width: 100%;
				background: currentColor;
				opacity: 0.1;
				top: 0;
				left: 0;
			}
		}

		.btn-input-box {
			position: relative;
			margin: 0 4px;

			&:before {
				content: '';
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
				left: 0;
				background: currentColor;
				opacity: 0.1;
			}

			.btn-input {
				position: relative;
				z-index: 1;
				height: 56px;
				width: 80px;
				line-height: 1;
				border: none;
				// background: transparent;
				text-align: center;
			}
		}

		.btn-minus,
		.btn-plus {
			position: relative;
			font-size: 45px;
			line-height: 56px;
			height: 56px;
			width: 56px;
			text-align: center;
			overflow: hidden;
			border-radius: 0 8px 8px 0;

			&:before {
				content: '';
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
				left: 0;
				background: currentColor;
				opacity: 0.1;
			}
		}

		.btn-minus {
			border-radius: 8px 0 0 8px;
		}
	}
}

.bottom-box {
	padding: 0 30px 50px 30px;
	display: flex;
	align-items: center;

	.br-left {
		border-radius: 44px 0 0 44px;
	}

	.br-right {
		border-radius: 0 44px 44px 0;
	}
}
</style>
